package cn.lisens.config;

import java.io.File;

import javax.servlet.Filter;
import javax.servlet.MultipartConfigElement;
import javax.servlet.ServletRegistration.Dynamic;

import org.springframework.web.filter.CharacterEncodingFilter;
import org.springframework.web.filter.DelegatingFilterProxy;
import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer;

import cn.lisens.common.controller.XssFilter;

public class MyWebAppInitializer extends AbstractAnnotationConfigDispatcherServletInitializer {

	private static final String UPLOAD_FOLDER = System.getProperty("java.io.tmpdir"); 
//	private File uploadDirectory = new File(System.getProperty("java.io.tmpdir"));
	
    private static final int MAX_UPLOAD_SIZE = 5 * 1024 * 1024; 
    
	@Override
	protected Class<?>[] getRootConfigClasses() {
		return null;
	}

	@Override
	protected Class<?>[] getServletConfigClasses() {
		return of(WebConfig.class);
	}

	@Override
	protected String[] getServletMappings() {
		return new String[]{"/"};
	}
	
	@Override
	protected Filter[] getServletFilters() {
		DelegatingFilterProxy delegateFilterProxy = new DelegatingFilterProxy();
	    delegateFilterProxy.setTargetBeanName("shiroFilterFactoryBean");
	    delegateFilterProxy.setTargetFilterLifecycle(true);
	    
	    CharacterEncodingFilter encodingFilter = new CharacterEncodingFilter();
        encodingFilter.setEncoding("UTF-8");
        encodingFilter.setForceEncoding(true);
        
	    return new Filter[]{
	    		delegateFilterProxy
	    		,encodingFilter
	    		,new XssFilter()
	    		};
	}
	
	@Override
	protected void customizeRegistration(Dynamic registration) {
		 MultipartConfigElement multipartConfigElement = new MultipartConfigElement(UPLOAD_FOLDER, 
		          MAX_UPLOAD_SIZE, MAX_UPLOAD_SIZE * 2L, MAX_UPLOAD_SIZE / 2);
		 registration.setMultipartConfig(multipartConfigElement);
	}
	
	@SafeVarargs
	private static <T> T[] of(T... values) {	//便利API，渐少new T[]代码
		return values;
	}
}
